// components/file-uploader/file-uploader.js
const { uploadService } = require('../../utils/upload-service.js');

Component({
  properties: {
    // 上传类型：single-单文件，multiple-多文件
    uploadType: {
      type: String,
      value: 'single'
    },
    // 最大文件数量（多文件上传时）
    maxCount: {
      type: Number,
      value: 9
    },
    // 文件选择来源
    sourceType: {
      type: Array,
      value: ['album', 'camera']
    },
    // 是否显示上传按钮
    showUploadButton: {
      type: Boolean,
      value: true
    },
    // 上传按钮文字
    buttonText: {
      type: String,
      value: '选择文件'
    },
    // 自定义样式类
    customClass: {
      type: String,
      value: ''
    },
    // 是否禁用
    disabled: {
      type: Boolean,
      value: false
    },
    // 文件类型限制
    accept: {
      type: String,
      value: 'all' // all, image, document, audio, video
    }
  },

  data: {
    uploading: false,
    uploadProgress: 0,
    fileList: []
  },

  methods: {
    /**
     * 选择文件
     */
    chooseFile() {
      if (this.data.disabled || this.data.uploading) {
        return;
      }

      const options = {
        count: this.properties.uploadType === 'single' ? 1 : this.properties.maxCount,
        sourceType: this.properties.sourceType,
        success: (res) => {
          this.handleFileSelected(res.tempFilePaths || res.tempFiles);
        },
        fail: (error) => {
          wx.showToast({
            title: '选择文件失败',
            icon: 'none'
          });
          console.error('选择文件失败:', error);
        }
      };

      // 根据接受的文件类型选择不同的API
      if (this.properties.accept === 'image') {
        wx.chooseImage(options);
      } else if (this.properties.accept === 'video') {
        wx.chooseVideo({
          sourceType: this.properties.sourceType,
          success: (res) => {
            this.handleFileSelected([res.tempFilePath]);
          },
          fail: options.fail
        });
      } else {
        // 通用文件选择（小程序基础库2.21.0+）
        wx.chooseMessageFile({
          count: options.count,
          type: this.getMessageFileType(),
          success: (res) => {
            const filePaths = res.tempFiles.map(file => file.path);
            this.handleFileSelected(filePaths);
          },
          fail: () => {
            // 降级到选择图片
            wx.chooseImage(options);
          }
        });
      }
    },

    /**
     * 获取消息文件类型
     */
    getMessageFileType() {
      const typeMap = {
        image: 'image',
        video: 'video',
        document: 'file',
        all: 'all'
      };
      return typeMap[this.properties.accept] || 'all';
    },

    /**
     * 处理文件选择结果
     */
    async handleFileSelected(filePaths) {
      if (!filePaths || filePaths.length === 0) {
        return;
      }

      // 显示加载状态
      this.setData({
        uploading: true,
        uploadProgress: 0
      });

      wx.showLoading({
        title: '上传中...',
        mask: true
      });

      try {
        if (this.properties.uploadType === 'single') {
          // 单文件上传
          const result = await uploadService.uploadFile(filePaths[0]);
          this.handleUploadSuccess([result]);
        } else {
          // 多文件上传
          const result = await uploadService.uploadMultipleFiles(filePaths, {
            onProgress: (progress) => {
              this.setData({
                uploadProgress: progress.progress
              });
              wx.showLoading({
                title: `上传中...${progress.progress}%`,
                mask: true
              });
            }
          });
          this.handleUploadSuccess(result.results, result.errors);
        }
      } catch (error) {
        this.handleUploadError(error);
      } finally {
        wx.hideLoading();
        this.setData({
          uploading: false,
          uploadProgress: 0
        });
      }
    },

    /**
     * 处理上传成功
     */
    handleUploadSuccess(results, errors = []) {
      const newFileList = results.map(result => ({
        id: Date.now() + Math.random(),
        url: result.url,
        fileName: result.fileName,
        fileType: result.fileType,
        fileSize: result.fileSize,
        uploadTime: new Date().toISOString()
      }));

      let fileList;
      if (this.properties.uploadType === 'single') {
        fileList = newFileList;
      } else {
        fileList = [...this.data.fileList, ...newFileList];
      }

      this.setData({ fileList });

      // 触发成功事件
      this.triggerEvent('success', {
        files: newFileList,
        allFiles: fileList,
        errors
      });

      // 显示成功提示
      const successCount = results.length;
      const errorCount = errors.length;
      
      if (errorCount === 0) {
        wx.showToast({
          title: `成功上传${successCount}个文件`,
          icon: 'success'
        });
      } else {
        wx.showToast({
          title: `上传完成，${successCount}成功，${errorCount}失败`,
          icon: 'none'
        });
      }
    },

    /**
     * 处理上传错误
     */
    handleUploadError(error) {
      console.error('文件上传失败:', error);
      
      wx.showToast({
        title: error.message || '上传失败',
        icon: 'none'
      });

      // 触发错误事件
      this.triggerEvent('error', {
        error: error.message || '上传失败'
      });
    },

    /**
     * 删除文件
     */
    deleteFile(e) {
      const index = e.currentTarget.dataset.index;
      const fileList = [...this.data.fileList];
      const deletedFile = fileList.splice(index, 1)[0];
      
      this.setData({ fileList });
      
      // 触发删除事件
      this.triggerEvent('delete', {
        file: deletedFile,
        index,
        allFiles: fileList
      });
    },

    /**
     * 预览文件
     */
    previewFile(e) {
      const index = e.currentTarget.dataset.index;
      const file = this.data.fileList[index];
      
      if (file.fileType === 'image') {
        const urls = this.data.fileList
          .filter(f => f.fileType === 'image')
          .map(f => f.url);
        
        wx.previewImage({
          urls,
          current: file.url
        });
      } else {
        // 其他文件类型的预览处理
        wx.showModal({
          title: '文件预览',
          content: `文件名：${file.fileName}\n文件类型：${file.fileType}\n文件大小：${this.formatFileSize(file.fileSize)}`,
          showCancel: false
        });
      }
    },

    /**
     * 格式化文件大小
     */
    formatFileSize(size) {
      if (size < 1024) {
        return size + 'B';
      } else if (size < 1024 * 1024) {
        return (size / 1024).toFixed(1) + 'KB';
      } else {
        return (size / (1024 * 1024)).toFixed(1) + 'MB';
      }
    },

    /**
     * 清空文件列表
     */
    clearFiles() {
      this.setData({ fileList: [] });
      this.triggerEvent('clear', {});
    }
  }
});